//
//  RegisterVC.m
//  NtoccShipper
//
//  Created by mac on 2019/11/12.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "RegisterVC.h"
#import "LogInVC.h"
#import "ImgVAouthCode.h"
#import "CJWKWebViewVC.h"
#import "CJCheckVersion.h"
#import "CJAppInfo.h"
@interface RegisterVC (){
    int time;
}
//@property (copy, nonatomic) NSArray *arrTitles;
//@property (strong, nonatomic) NSArray *arrContent;
//@property (strong, nonatomic) CJButton *btnSave;
////@property (nonatomic,strong) CJButton *btnGetCode;
//
//@property (nonatomic,strong) CJButton *btnSendGoodsPerson; //发货人
//@property (nonatomic,strong) CJButton *btnSendGoodsCompany;
//@property (nonatomic,strong) CJButton *btnAgree;
//@property (nonatomic,strong) CJButton *btnUserProtocol;
//@property (nonatomic,strong) CJButton *btnEye;
////@property (nonatomic,strong) CJButton *btnSelectBranchCode; //选择机构代码

// new
@property (nonatomic,strong) FlexTouchView *touvhViewGetBranchCode;
@property (nonatomic,copy) NSString *strBranchCode; // 机构代码
@property (nonatomic,strong) CJTextField *fiedBranchCode;

@property (nonatomic,strong) FlexTouchView *toucViewGetAouthCode;
@property (nonatomic,strong) CJTextField *fieldPhoneNum;
@property (nonatomic,strong) CJLabel *labCodeTime;

@property (nonatomic,strong) CJTextField *fieldAouthCode; // 验证码

@property (nonatomic,strong) CJTextField *fieldPW;
@property (nonatomic,strong) CJTextField *fieldPWSure;

@property (nonatomic,strong) CJImageView *imgSecureEntry;
@property (nonatomic,strong) NSString *strSecureEntry; //1 q安全模式
//@property (nonatomic,strong) CJTextField *fieldName;

@property (nonatomic,strong) NSString *strDriverType;  // 2发货人 3 发货企业
@property (nonatomic,strong) CJImageView *imgVPerson;
@property (nonatomic,strong) CJImageView *imgVCompany;

@property (nonatomic,copy) NSString *strIsAgree;
@property (nonatomic,strong) CJImageView *imgVAgree;
@property (nonatomic,strong) CJLabel *labXieYiTitle;

@property (nonatomic,strong) UIView *viewBranchLine;

@end

@implementation RegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:@"注册"];
    [self setBackLeftButton:@""];

    [self createView];
    self.strSecureEntry = @"1";
    self.strDriverType = @"2";
    self.strIsAgree = @"1";
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.touvhViewGetBranchCode.userInteractionEnabled = YES;
    @weakify(self);
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {
        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        if (list.count > 0) {
            NSDictionary *dic = list[0];
            self.fiedBranchCode.text = [CJControl getThreeUnaryValueStr:dic[@"groupName"]];
            self.strBranchCode = [CJControl getThreeUnaryValueStr:dic[@"code"]];
        }

    }];
    
    if ([CJControl getHideBranche]) {
        self.touvhViewGetBranchCode.hidden = YES;
        self.viewBranchLine.hidden = YES;
    }else{
        self.touvhViewGetBranchCode.hidden = NO;
        self.viewBranchLine.hidden = NO;
    }
}

- (void)createView{
    
    //
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"RegisterView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;

    if (@available(iOS 12.0, *)) {
        self.fieldPW.textContentType = UITextContentTypeOneTimeCode;
        self.fieldPWSure.textContentType = UITextContentTypeOneTimeCode;

    } else {
        // Fallback on earlier versions
    }
    
    self.labXieYiTitle.text = CJStringWithFormat(@"《%@APP服务协议》",[CJAppInfo appName]);
    self.labXieYiTitle.textColor = [UIColor cjMainColorText];
    
    [header layoutIfNeeded];
    [self.view addSubview:header];

}


/// 密码是否安全模式
- (void)touchViewSecureTextEntryAction{
    
    if (self.strSecureEntry.intValue == 1) {
        self.strSecureEntry = @"0";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_open_eye"];
        self.fieldPW.secureTextEntry = NO;
        self.fieldPWSure.secureTextEntry = NO;
    }else{
        self.strSecureEntry = @"1";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_close_eye"];
        self.fieldPW.secureTextEntry = YES;
        self.fieldPWSure.secureTextEntry = YES;
    }
}


- (void)touchViewSelectPersionAction{
    
    self.strDriverType = @"2";
    self.imgVPerson.image = [UIImage imageNamed:@"zcj_selectedCir"];
    self.imgVCompany.image = [UIImage imageNamed:@"zcj_unSelectedCir"];
}

- (void)touchViewSelectComapnyAction{
    
    self.strDriverType = @"3";
    self.imgVPerson.image = [UIImage imageNamed:@"zcj_unSelectedCir"];
    self.imgVCompany.image = [UIImage imageNamed:@"zcj_selectedCir"];
}


- (void)btnSaveAction{

    [self.view endEditing:NO];
    if (![CJRegular getcheckPhone:self.fieldPhoneNum.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldPhoneNum] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];

        }];
    }else if (![CJRegular getPhoneNumAouth:self.fieldAouthCode.text]){
       
            [CJAlert showStringDismissWithDelay:@"请填写验证码"];

    }else if (IsStrEmpty(self.fieldPW.text)){
        [[[AFViewShaker alloc] initWithView:self.fieldPW] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请填写密码"];

        }];
  
    }else if (IsStrEmpty(self.fieldPWSure.text)){
        [[[AFViewShaker alloc] initWithView:self.fieldPWSure] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请再次输入密码"];

        }];

    }else if (![self.fieldPWSure.text isEqualToString:self.fieldPW.text]){
        [[[AFViewShaker alloc] initWithView:self.fieldPWSure] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"两次密码不一致"];

        }];
        [[[AFViewShaker alloc] initWithView:self.fieldPW] shakeWithDuration:[ShakerTime floatValue] completion:^{
        }];

    }
//    else if (IsStrEmpty(self.fieldName.text)){
//        [[[AFViewShaker alloc] initWithView:self.fieldName] shakeWithDuration:[ShakerTime floatValue] completion:^{
//            [CJAlert showStringDismissWithDelay:@"请填写姓名"];
//        }];
//
//    }
    else if ([self.strDriverType isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择注册类型"];
    }else if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];

    }
    else if (self.strIsAgree.intValue == 0){
            [CJAlert showStringDismissWithDelay:@"请阅读并同意协议"];
    }
    
    else{

        NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/party/register",CJBaseUrl);

        NSDictionary *dicPra = @{
            @"branchCode":self.strBranchCode,
            //                                 @"name":self.fieldName.text,
            @"partyType":self.strDriverType,
            @"phone":self.fieldPhoneNum.text,
            @"upass":[CJControl base64:self.fieldPW.text],
            @"verifyCode":self.fieldAouthCode.text
        };
        @weakify(self);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:PostType url:strUrl parameters:dicPra status:OperationTip success:^(id  _Nonnull responseObject) {
            @strongify(self);
            [CJControl clearAllUserDefaultsData];
            LogInVC *vc = [[LogInVC alloc] init];
            vc.isRegsiter = YES;
            [self pushVc:vc];
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }
   
    
}
- (void)touchViewPhoneVerCodeAction{
    [self.view endEditing:NO];
     if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
         return;
    }
  
    if (![CJRegular getcheckPhone:self.fieldPhoneNum.text]) {
         [[[AFViewShaker alloc] initWithView:self.fieldPhoneNum] shakeWithDuration:[ShakerTime floatValue] completion:^{
             [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];

         }];
    }else{


        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/party/validPhoneNoError",CJBaseUrl);
        NSDictionary *dicPar = @{@"phone":CJStringWithFormat(@"%@",self.fieldPhoneNum.text),
                                 @"branchCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
                                };

        @weakify(self);
        [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {

//            {
//                "msg": "手机号没有注册",
//                "data": "no",
//                "status": 0
//            }
            @strongify(self);
            NSString *strData = (NSString *)responseObject;
            
            if ([strData isEqualToString:@"no"]) {
//                [ws getSendVerificationCode];
                
                [[ImgVAouthCode shared] initWithPhoneNum:self.fieldPhoneNum.text ClickOnSure:^(NSString * _Nonnull strSure) {
                    [self getSendVerificationCodeWithImageCode:strSure];
                 } ClickOnCancle:^(NSString * _Nonnull strCancle) {
                     
                 }];

            }else{
                [CJAlert showStringDismissWithDelay:@"手机号已注册"];
            }
            
            
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);

        }];

    }
    
}

- (void)getSendVerificationCodeWithImageCode:(NSString *)imgVCode{

     if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
         return;
    }
    if (![CJRegular getcheckPhone:self.fieldPhoneNum.text]) {
        [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];
         return;
    }
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/sms/sendVerificationCode",CJBaseUrl);
     NSDictionary *dicPar = @{@"phone":CJStringWithFormat(@"%@",self.fieldPhoneNum.text),
                              @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
                              @"imageCode":imgVCode
                             };
     
     @weakify(self);
     [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
         
         DLog(@"++++++++%@",responseObject);
         @strongify(self);
         [CJAlert showStringDismissWithDelay:@"发送成功"];
         self.toucViewGetAouthCode.userInteractionEnabled = NO;
         time = 60;
         [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireM:) userInfo:nil repeats:YES];
         self.touvhViewGetBranchCode.userInteractionEnabled = NO;
         
     } failure:^(NSError * _Nonnull error) {
         DLog(@"++++++++%@",error);
         
     }];
}

- (void)timerFireM:(NSTimer *)theTimer{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",time];
    self.labCodeTime.text = str;
    time--;
    if (time==0) {
        [theTimer invalidate];
        time=60;
        self.labCodeTime.text = @"验证码";
        self.toucViewGetAouthCode.userInteractionEnabled = YES;
    }
}


- (void)touchViewAgreeAction{
    
    if (self.strIsAgree.intValue == 1) {
        self.strIsAgree = @"0";
        self.imgVAgree.image = UIImageNamed(@"zcj_unSelected");

    }else{
        self.strIsAgree = @"1";
        self.imgVAgree.image = UIImageNamed(@"selected");
    }
}


/// 协议
- (void)touchViewUserProtocolAction{
    
    //    0716 release0716-agreement-newhtml 修改协议地址传参agreementType：协议类型:1=司机端隐私协议/2=司机端用户协议/3=司机端注销协议/4=司机端物流协议/5=接单协议/6=司机端SDK协议/7=货主端隐私协议/8=货主端用户协议/9=货主端注销协议/10=货主端物流协议/11=货主端SDK协议/12=PC端隐私协议/13=PC端用户协议/14=PC端物流协议/15=网商协议  例如 /agreement/agreement.html?agreementType=1
    CJWKWebViewVC *vc = [CJWKWebViewVC new];
    vc.strTitle = @"服务协议";
    vc.useUTF8 = YES;
    vc.strUrl = CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=8",CJBaseUrl);
    [self pushVc:vc];
}

#pragma mark ----------选择机构 ----
-(void)btnGetBranchCodeListAction{

    [self.view endEditing:NO];

    @weakify(self);
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {
        
        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        NSMutableArray *arrMutar = [[NSMutableArray alloc]init];
        NSMutableArray *arrMutarCodes = [[NSMutableArray alloc]init];

        if (list.count > 0) {

            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [arrMutar addObject:obj[@"groupName"]];
                [arrMutarCodes addObject:obj[@"code"]];
            }];
        }
        [self btnSelectList:arrMutar listCodes:arrMutarCodes title:@""];
        
    }];
}


- (void)btnSelectList:(NSArray *)list listCodes:(NSMutableArray *)arryCodes title:(NSString *)strTitle{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = list;
    @weakify(self);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        
        @strongify(self);
        self.fiedBranchCode.text = resultModel.selectValue;
        self.strBranchCode = arryCodes[resultModel.index];
   
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}


@end
